package com.aichan.aibi.handler;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.aichan.aibi.common.BaseResponse;
import com.aichan.aibi.model.entity.login.LoginUser;
import com.aichan.aibi.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * @author mengyu
 * 无权限异常处理器 (AccessDeniedException)
 * @date 2024/03/03 9:42
 */
@Component
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(!Objects.isNull(user)){
            log.info("access denied: {}",user.getUser().getId());
        }
        // 包装Response对象并写入HttpServletResponse
        BaseResponse<String> result = BaseResponse.error(HttpStatus.HTTP_FORBIDDEN,"权限不足:"+accessDeniedException.getMessage());
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);
    }
}
